// 空闲活动频率量表逻辑处理文件
import { leisureActivityConfig } from './leisureActivityConfig.js';

/**
 * 计算空闲活动评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估结果
 */
export function calculateLeisureActivityAssessment(formData) {
  // 计算各项活动得分
  const activityScores = {};
  let totalScore = 0;
  let answeredCount = 0;
  
  leisureActivityConfig.leisureActivities.forEach(activity => {
    const score = formData[activity.id];
    if (score !== undefined && score !== null && score !== '') {
      activityScores[activity.id] = parseInt(score);
      totalScore += parseInt(score);
      answeredCount++;
    } else {
      activityScores[activity.id] = null;
    }
  });
  
  // 计算平均分
  const averageScore = answeredCount > 0 ? (totalScore / answeredCount).toFixed(2) : 0;
  
  // 统计各频率分布
  const frequencyDistribution = {
    1: 0, // 从不参加
    2: 0, // 一年数次
    3: 0, // 一月数次
    4: 0, // 一周数次
    5: 0  // 几乎每天
  };
  
  Object.values(activityScores).forEach(score => {
    if (score !== null && score >= 1 && score <= 5) {
      frequencyDistribution[score]++;
    }
  });
  
  // 计算活动参与度等级
  const participationLevel = calculateParticipationLevel(averageScore);
  
  // 获取健身器材选择
  const fitnessEquipment = formData.fitnessEquipment || [];
  
  return {
    activityScores: activityScores,
    totalScore: totalScore,
    averageScore: parseFloat(averageScore),
    answeredCount: answeredCount,
    frequencyDistribution: frequencyDistribution,
    participationLevel: participationLevel,
    fitnessEquipment: fitnessEquipment,
    statistics: {
      neverParticipate: frequencyDistribution[1],
      yearlyParticipate: frequencyDistribution[2],
      monthlyParticipate: frequencyDistribution[3],
      weeklyParticipate: frequencyDistribution[4],
      dailyParticipate: frequencyDistribution[5]
    }
  };
}

/**
 * 计算活动参与度等级
 * @param {number} averageScore - 平均分
 * @returns {Object} 参与度等级信息
 */
function calculateParticipationLevel(averageScore) {
  if (averageScore >= 4.5) {
    return {
      level: '高',
      description: '活动参与度很高，几乎每天都参与多种活动',
      color: 'green'
    };
  } else if (averageScore >= 3.5) {
    return {
      level: '中高',
      description: '活动参与度较高，经常参与活动',
      color: 'lightgreen'
    };
  } else if (averageScore >= 2.5) {
    return {
      level: '中等',
      description: '活动参与度中等，偶尔参与活动',
      color: 'orange'
    };
  } else if (averageScore >= 1.5) {
    return {
      level: '中低',
      description: '活动参与度较低，很少参与活动',
      color: 'lightcoral'
    };
  } else {
    return {
      level: '低',
      description: '活动参与度很低，几乎不参与活动',
      color: 'red'
    };
  }
}

/**
 * 生成空闲活动评估报告
 * @param {Object} assessmentResult - 评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估报告
 */
export function generateLeisureActivityReport(assessmentResult, formData) {
  const frequencyLabels = {
    1: '从不参加',
    2: '一年数次',
    3: '一月数次',
    4: '一周数次',
    5: '几乎每天'
  };
  
  const basicInfo = {
    patientName: formData.patientName || '',
    patientId: formData.patientId || '',
    recordDate: formData.recordDate || '',
    age: formData.age || '',
    gender: formData.gender || '',
    phone: formData.phone || '',
    measurementLocation: formData.measurementLocation || '',
    measurementPerson: formData.measurementPerson || '',
    remarks: formData.remarks || ''
  };
  
  const activities = leisureActivityConfig.leisureActivities.map(activity => {
    const score = assessmentResult.activityScores[activity.id];
    return {
      id: activity.id,
      label: activity.label,
      score: score,
      frequency: score ? frequencyLabels[score] : '未填写'
    };
  });
  
  const summary = {
    totalScore: assessmentResult.totalScore,
    averageScore: assessmentResult.averageScore,
    answeredCount: assessmentResult.answeredCount,
    participationLevel: assessmentResult.participationLevel,
    frequencyDistribution: assessmentResult.frequencyDistribution,
    fitnessEquipment: assessmentResult.fitnessEquipment
  };
  
  return {
    basicInfo: basicInfo,
    activities: activities,
    summary: summary,
    statistics: assessmentResult.statistics
  };
}

/**
 * 验证空闲活动表单数据
 * @param {Object} formData - 表单数据
 * @returns {Object} 验证结果
 */
export function validateLeisureActivityForm(formData) {
  const errors = [];
  const warnings = [];
  
  // 个人信息字段已改为选填，不再进行必填验证
  // recordDate 根据配置可能仍然是必填的，但这里先移除验证
  // 如果这个字段在配置中标记为必填，会在组件层面进行验证
  
  // 验证活动频率（至少填写一部分）
  let answeredCount = 0;
  leisureActivityConfig.leisureActivities.forEach(activity => {
    const score = formData[activity.id];
    if (score !== undefined && score !== null && score !== '') {
      answeredCount++;
    }
  });
  
  if (answeredCount === 0) {
    errors.push('请至少填写一项活动的参与频率');
  }
  
  // 验证健身器材选择（如果选择了健身器材锻炼）
  if (formData.Q07 && parseInt(formData.Q07) >= 2) {
    // 如果选择了健身器材锻炼（频率>=2），建议填写健身器材类型
    if (!formData.fitnessEquipment || formData.fitnessEquipment.length === 0) {
      warnings.push('您选择了健身器材锻炼，建议填写最经常使用的健身器材类型');
    } else if (formData.fitnessEquipment.length > 3) {
      errors.push('健身器材类型最多只能选择3项');
    }
  }
  
  return {
    isValid: errors.length === 0,
    errors,
    warnings,
    hasWarnings: warnings.length > 0
  };
}

export default {
  calculateLeisureActivityAssessment,
  generateLeisureActivityReport,
  validateLeisureActivityForm
};

